from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from werkzeug.exceptions import HTTPException
import logging

# 初始化扩展
db = SQLAlchemy()
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    
    # 配置日志
    logging.basicConfig(level=logging.DEBUG)
    
    # 配置
    app.config.from_object('config.Config')
    
    # 初始化扩展
    # CORS(app, resources={
    #     r"/*": {
    #         "origins": app.config['CORS_ORIGINS'],
    #         "methods": app.config['CORS_METHODS'],
    #         "allow_headers": app.config['CORS_ALLOW_HEADERS']
    #     }
    # })

    CORS(app, resources={
        r"/*": {  # 匹配所有路径
            "origins": "*",  # 允许所有来源
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"],  # 所有常用方法
            "allow_headers": "*",  # 允许所有头部
            "supports_credentials": True,  # 允许凭证
            "expose_headers": "*",  # 暴露所有头部
            "max_age": 86400  # 预检结果缓存时间
        }
    })
    
    db.init_app(app)
    jwt.init_app(app)
    
    # 请求日志
    @app.before_request
    def log_request_info():
        app.logger.debug('Headers: %s', request.headers)
        app.logger.debug('Body: %s', request.get_data())
        app.logger.debug('Method: %s', request.method)
        app.logger.debug('URL: %s', request.url)
    
    # 响应头处理
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return response
    
    # 注册蓝图
    from app.routes.auth import auth_bp
    from app.routes.products import products_bp
    from app.routes.orders import orders_bp
    
    app.register_blueprint(auth_bp, url_prefix='/api')
    app.register_blueprint(products_bp, url_prefix='/api')
    app.register_blueprint(orders_bp, url_prefix='/api')
    
    # 错误处理
    @app.errorhandler(HTTPException)
    def handle_http_error(error):
        return jsonify({
            'error': error.description,
            'status_code': error.code
        }), error.code
    
    @app.errorhandler(Exception)
    def handle_error(error):
        return jsonify({
            'error': str(error),
            'status_code': 500
        }), 500
    
    return app 